<?php
/**
 * Description:
 *
 * @author      Eden
 * @datetime    2017/1/11 00:53
 * @copyright   WuHan HuQi Technology Co.,Ltd.
 * @url         http://cnhuqi.com
 */

class Goods extends WX_Controller
{
    // 基地ID
    private $goodsId = 0;
    private $userId = 0;
    private $width = 640;
    private $height = 360;

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 商品详情
     * @return bool
     */
    public function getGoodsDetail()
    {

        $this->goodsId = (int) $this->input->get('goodsId');

        $db = clone($this->db);
        $q = $db->select('g.goodsName, g.description, g.baseId, bc.name as categoryName, b.name as baseName, g.thumb,
            g.bannerThumb, g.streamId, g.content, g.pv, g.likes, g.liveUrl,
            g.stars, g.comments, g.price, g.minPrice, g.maxPrice, g.activity, g.stock, g.unit, g.expType, g.expAmount, g.sold, g.created, g.status')
            ->from('base_goods as g')
            ->join('base as b', 'b.id = g.baseId')
            ->join('base_category as bc', 'bc.id = g.categoryId')
            ->where('g.status = 1')
            ->where('g.id', $this->goodsId)
            ->get();
        $row = $q->row_array();

        if (empty($row)) {
            return false;
        }

        $thumb = !empty($row['bannerThumb']) ? $row['bannerThumb'] : $row['thumb'];
        $row['goodsId'] = $this->goodsId;
        $row['baseId'] = intval($row['baseId']);
        $row['thumb'] = thumb($thumb, 800, 800);
        $row['pv'] = intval($row['pv']);
        $row['alertThumb'] = thumb($row['thumb'], 200, 200);
        $row['likes'] = intval($row['likes']);
        $row['stock'] = intval($row['stock']);
        $row['sold'] = intval($row['sold']);
        $row['stars'] = intval($row['stars']);
        $row['liveUrl'] = value($row, 'liveUrl', '');
        $row['expType'] = intval($row['expType']);
        $row['expAmount'] = intval($row['expAmount']);
        $row['expAmount_format'] = money_format('%i', $row['expAmount'] / 100);
        $row['created'] = formateTimeStamp($row['created']);
        $row['status'] = $row['status'] == 1 ? 'onSale' : 'offSale';
        $row['related'] = $this->_getRelatedGoods();
        $row['shareUrl'] = WX_URL . '/share?goodsId=' . $this->goodsId . '&puserid=' . $this->userid;
        $row['minPrice'] = !empty($row['minPrice']) ? money_format('%i', $row['minPrice'] / 100) : 0;
        $row['maxPrice'] = !empty($row['maxPrice']) ? money_format('%i', $row['maxPrice'] / 100) : 0;
        $row['collected'] = $this->_checkCollected($this->userid);
        $row['activity'] = $row['activity'] == 1 ? true : false;

        // get rules
        $row['rules'] = $this->_getRules($this->goodsId);
        // get thumbs
        $row['thumbs'] = $this->_getThumbs($this->goodsId);

        $send['state'] = true;
        $send['data'] = $row;
        $send['comments'] = $this->_getLatestTwoComments();
        @statIncr('pv');
        $this->output->send($send);
    }

    /**
     * 总销量
     * @param int $goodsId
     * @return mixed
     */
    public function _getSaleStock($goodsId = 0)
    {
        $db = clone ($this->db);
        $db->where('orderId', $goodsId);
        return $db->count_all_results('user_order_goods');
    }

    /**
     * 最近评论
     * @return mixed
     */
    private function _getLatestTwoComments()
    {
        $this->load->model('common/Comment_Model', 'comment');
        $comments = $this->comment->lists($this->goodsId, 0, 2);
        return $comments;
    }

    /**
     * 是否收藏商品
     * @param $userId
     * @return bool
     */
    private function _checkCollected($userId)
    {
        $db = clone($this->db);
        $db->where(['userId' => $userId, 'goodsId' => $this->goodsId]);
        $q = $db->get('user_collect');
        if (!empty($q->row_array())) {
            return true;
        }
        return false;
    }

    /**
     * @param $goodsid
     * @return array
     */
    private function _getThumbs($goodsid)
    {
        $db  = clone($this->db);
        $q = $db->get_where('base_goods_thumb', ['goods_id' => $goodsid]);
        $rows = $q->result_array();
        if (empty($rows)) {
            return [];
        }

        foreach($rows as &$item) {
            $item['thumb_view'] = thumb($item['thumb'], 800, 800);
        }

        return $rows;
    }

    /**
     * @param $goodsid
     * @return mixed
     */
    private function _getRules($goodsid)
    {
        $db = clone($this->db);
        $q = $db->get_where('base_goods_rule', ['goods_id' => $goodsid, 'status' => 6]);
        $rows = $q->result_array();
        if (!empty($rows)) foreach ($rows as &$item) {
            $price = $this->userType == 1 ? intval($item['purchaserPrice']) : intval($item['salePrice']);
            $item['oldPrice'] = intval($item['oldPrice']);
            $item['salePrice'] = $price;
            $item['oldPrice_format'] = money_format('%i', $item['oldPrice'] / 100);
            $item['salePrice_format'] = money_format('%i', $price / 100);
        }
        return $rows;
    }

    /**
     * 直播
     * @param int $streamId
     * @return mixed
     */
    protected function _getStreamUrl($streamId = 0)
    {
        $db = clone($this->db);
        $q = $db->select('videoUrlHD, videoUrlSD, status')->get_where('stream_device', array('id' => $streamId));
        return $q->row_array();
    }

    /**
     * 相关产品
     * @return array
     */
    private function _getRelatedGoods()
    {
        $detail= array(
            'total' => 0,
            'data' => []
        );
        $db = clone($this->db);
        $q = $db->select('id, goodsName, thumb, minPrice, minPurPrice, stock, created')
            ->from('base_goods')
            ->order_by('pv', 'DESC')
            ->limit(8)
            ->where(array('status' => 1))
            ->where('stock > 0')
            ->get();
        $rows = $q->result_array();
        if (empty($rows)){
            return $detail;
        }

        $results = $this->_doAfterSelectGoods($rows);
        $detail['total'] = count($results);
        $detail['data'] = $results;
        return $detail;
    }

    /**
     * 处理返回结果
     * @param array $goods
     * @return array
     */
    private function _doAfterSelectGoods($goods = array())
    {
        $results = [];
        foreach($goods as $item) {
            $results[] = array(
                'goodsId' => intval($item['id']),
                'goodsName' => value($item, 'goodsName'),
                'thumb' => thumb($item['thumb'], 200, 200),
                'stock' => intval($item['stock']),
                'price' => $this->userType == 1 ? money_format('%i', $item['minPurPrice'] / 100) : money_format('%i', $item['minPrice'] / 100),
                'created' => formateTimeStamp($item['created']),
                'isLive' => !empty($item['streamId'])
            );
        }
        return $results;
    }
}